<template>
  <el-container class="order-history-container">
    <el-main>
      <el-card>
        <template #header>
          <h2>我的订单</h2>
        </template>

        <div class="filters">
          <el-form :inline="true" :model="filterParams">
            <el-form-item label="订单状态">
              <el-select v-model="filterParams.status" placeholder="全部状态" clearable @change="handleFilterChange">
                <el-option label="处理中" value="processing"></el-option>
                <el-option label="已发货" value="shipped"></el-option>
                <el-option label="已完成" value="completed"></el-option>
                <el-option label="已取消" value="cancelled"></el-option>
                <el-option label="待付款" value="pending_payment"></el-option>
              </el-select>
            </el-form-item>
            <!-- Future: Add date range picker or order number search -->
          </el-form>
        </div>

        <div v-if="loading" class="loading-spinner">
          <el-progress :percentage="50" :indeterminate="true" />
          <p>加载订单列表中...</p>
        </div>
        <div v-else-if="error" class="error-message">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
        <div v-else-if="!orders.length" class="empty-orders">
          <el-empty description="您还没有任何订单。">
            <el-button type="primary" @click="goToProducts">去购物</el-button>
          </el-empty>
        </div>
        <div v-else>
          <el-table :data="orders" style="width: 100%">
            <el-table-column prop="order_number" label="订单号" width="200">
                <template #default="scope">
                    <el-link type="primary" @click="goToOrderDetail(scope.row.order_number)">{{ scope.row.order_number }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="下单时间" width="180">
              <template #default="scope">{{ formatDateTime(scope.row.created_at) }}</template>
            </el-table-column>
            <el-table-column prop="total_amount" label="订单金额" width="120">
              <template #default="scope">¥{{ scope.row.total_amount }}</template>
            </el-table-column>
            <el-table-column prop="status_display" label="订单状态" width="120">
                <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status_display || scope.row.status }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" @click="goToOrderDetail(scope.row.order_number)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-if="pagination.total > 0"
              background
              layout="prev, pager, next, total"
              :total="pagination.total"
              :current-page.sync="pagination.currentPage"
              :page-size="pagination.pageSize"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import orderService from '../api/order.service';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();

const orders = ref([]);
const loading = ref(true);
const error = ref(null);

const filterParams = reactive({
  status: route.query.status || '' // Initialize from URL query
});

const pagination = reactive({
  currentPage: parseInt(route.query.page) || 1, // Initialize from URL query
  pageSize: 10, // Or get from API if configurable
  total: 0,
});

const fetchOrders = async () => {
  loading.value = true;
  error.value = null;
  try {
    const params = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      status: filterParams.status || null, // Send null if empty for backend to ignore
    };
    const response = await orderService.getOrders(params);
    orders.value = response.data; 
    // Assuming API response includes pagination metadata in a "meta" object like:
    // response.meta = { current_page: 1, last_page: 5, per_page: 10, total: 50 }
    if (response.meta) {
        pagination.currentPage = response.meta.current_page;
        pagination.total = response.meta.total;
        pagination.pageSize = response.meta.per_page;
    }
  } catch (err) {
    console.error('获取订单列表失败:', err);
    error.value = err.message || '获取订单列表失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return 'N/A';
  try {
    return new Date(dateTimeString).toLocaleString('zh-CN', {
      year: 'numeric', month: 'short', day: 'numeric',
      hour: '2-digit', minute: '2-digit'
    });
  } catch (e) {
    return dateTimeString;
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case 'processing':
      return 'warning';
    case 'shipped':
      return 'primary';
    case 'completed':
      return 'success';
    case 'cancelled':
      return 'danger';
    case 'pending_payment':
      return 'info';
    default:
      return 'info';
  }
};

const handleFilterChange = () => {
  pagination.currentPage = 1; // Reset to first page when filters change
  updateRouterQuery();
  // fetchOrders(); // fetchOrders will be called by the watcher
};

const handlePageChange = (newPage) => {
  pagination.currentPage = newPage;
  updateRouterQuery();
  // fetchOrders(); // fetchOrders will be called by the watcher
};

const updateRouterQuery = () => {
    const query = {};
    if (filterParams.status) query.status = filterParams.status;
    if (pagination.currentPage > 1) query.page = pagination.currentPage;
    // router.push({ query }); // This causes re-fetch if query changes
    // Use replace to avoid adding too many history entries for simple filter/page changes
    router.replace({ query: Object.keys(query).length ? query : {} });
};

watch([() => route.query.status, () => route.query.page], ([newStatus, newPage]) => {
    filterParams.status = newStatus || '';
    pagination.currentPage = parseInt(newPage) || 1;
    fetchOrders();
}, { immediate: true }); // immediate: true to run on initial load


const goToProducts = () => {
  router.push({ name: 'Products' });
};

const goToOrderDetail = (orderNumber) => {
  router.push({ name: 'OrderDetail', params: { orderNumber } });
};

// No onMounted needed if watch has immediate: true
// onMounted(() => {
//   fetchOrders(); 
// });

</script>

<style scoped>
.order-history-container {
  padding: 20px;
}

.filters {
  margin-bottom: 20px;
}

.loading-spinner,
.error-message,
.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table .el-link {
    font-weight: normal;
}
</style> 